package com.sunnuwell.demo.service.impl;

import com.sunnuwell.demo.common.exception.AdException;
import com.sunnuwell.demo.constant.Constants;
import com.sunnuwell.demo.entity.Resource;
import com.sunnuwell.demo.entity.Role;
import com.sunnuwell.demo.repository.ResourceRepository;
import com.sunnuwell.demo.service.ResourceService;
import com.sunnuwell.demo.service.RoleService;
import com.sunnuwell.demo.vo.ResourceVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: entry
 * @description: 资源菜单service
 * @author: Mr.lv
 * @create: 2019-04-28 09:39
 **/
@Service
public class ResourceServiceImpl implements ResourceService {

    private ResourceRepository resourceRepository;
    private RoleService roleService;

    public ResourceServiceImpl(ResourceRepository resourceRepository, RoleService roleService) {
        this.resourceRepository = resourceRepository;
        this.roleService = roleService;
    }

    @Override
    public List<Resource> getAllResource() {
        return resourceRepository.findAll();
    }

    @Override
    public String addResource(ResourceVo resource) throws AdException {
        // 检查参数
        if (!resource.validate()) {
            throw new AdException(-1,Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        resourceRepository.save(new Resource(
                resource.getRid(), resource.getPath(), resource.getComponent(), resource.getRedirect(), resource.getName(), resource.getMeta(),
                resource.getChildren(), resource.getHidden()
        ));
        return Constants.ErrorMsg.OPERATION_SUCCESS;
    }

    @Override
    public String deleteResource(ResourceVo resourceVo) throws AdException {
        if (!resourceVo.volidateRid()) {
            throw new AdException(-1,Constants.ErrorMsg.REQUEST_PARAM_ERROR);
        }
        // 判断该资源菜单有没有被角色绑定
        List<Role> roles = roleService.getAllRole();
        for (Role r: roles
             ) {
            if (null != r.getResources()) {
                for (Resource res: r.getResources()
                     ) {
                    if (res.getRid().equals(resourceVo.getRid())) {
                        throw new AdException(-1,"该资源菜单已被角色绑定，请先接触绑定关系");
                    }
                }
            }
        }
        Resource resource = new Resource();
        resource.setRid(resourceVo.getRid());
        resourceRepository.delete(resource);
        return Constants.ErrorMsg.OPERATION_SUCCESS;
    }
}